# Version 0.1 BNL, December 2, 2004
# This code is in the public domain, no warranty etc, use it at your own risk
from UserList import UserList

class MultiSplit(UserList):
  ''' Take a string,s, and a list containing items to split on, and
    when instantiated, return a list of lists identifying substrings
    and what precedes it.'''

  def __init__(self,s,listofsplitters):

    slist=[x for x  in listofsplitters]
    UserList.__init__(self)
    result=[(None,s)]
    while len(slist) > 0:
        results=[]
        item=slist.pop()
        for edge,substring in result:
            #if substring != '':
                splitted=substring.split(item)
                if len(splitted)<>1:
                    results.append([edge,splitted[0]])
                    for word in splitted[1:]:
                        results.append([item,word])
                else:
                    results.append([edge,substring])
            #else:
            #    results.append(edge,substring)
        result=results
    #get rid of meaningless first term
    if result[0][0]==None: result[0]=['',results[0][1]]
    if result[0]==['',''] and len(result)>1: result=result[1:]
    
    self.data=result

  def join(self):
      ''' Return version of self as a concatenated string '''
      result=''
      for item in self.data:
          result='%s%s%s'% (result,item[0],item[1])
      return result
          
if __name__=='__main__':

    # test it
    input = 'abcn def 12 ghin xy adsf'
    result=MultiSplit(input,['n','12','xy'])
    print result
    print result.join()
    input = '12341231'
    x=MultiSplit(input,['1','4'])
    print x
    print x.join()
    print MultiSplit('',['1'])

